package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuMapProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.BaiDuMapUtils;
import com.sky.utils.MapUtils;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BaiDuMapProperties baiDuMapProperties;
    @Autowired
    WebSocketServer webSocketServer;
    @Autowired
    AdiminOrderMapper adiminOrderMapper;

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) throws Exception {

        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart =  ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        String shopAddress = baiDuMapProperties.getShopAddress();

        LinkedHashMap shopLocation = BaiDuMapUtils.Location(shopAddress);
        if (shopLocation == null|| shopLocation.size() == 0) {
            throw new OrderBusinessException("您输入的地址为空或地址有误");
        }
        System.out.println(shopLocation);
        String userAddress = address.getDetail();
        LinkedHashMap userLocation = BaiDuMapUtils.Location(userAddress);
        if (userLocation == null|| userLocation.size() == 0) {
            throw new OrderBusinessException("您输入的地址为空或地址有误");
        }
        System.out.println(userLocation);

        String origin1 = shopLocation.get("lng").toString();
        String origin2 = shopLocation.get("lat").toString();
        String originData = origin2 + "," + origin1;
        String destination1 = userLocation.get("lng").toString();
        String destination2 = userLocation.get("lat").toString();
        String destinationData = destination2 + "," + destination1;

        System.out.println(originData);
        System.out.println(destinationData);

        Routes distance = MapUtils.Distance( originData,  destinationData);
        if (distance == null) {
            throw new AddressBookBusinessException("百度api调用失败");
        }
        System.out.println(distance.getTotalDistance());
        if (distance.getTotalDistance()/1000 > 5){
            throw new OrderBusinessException("距离过远下单失败");
        }


        Orders orders = new Orders();

        System.out.println("距离:"+distance.getTotalDistance());
        System.out.println("时间:"+distance.getTotalDuration());

        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis())+userId);
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(address.getDetail());
        orders.setDeliveryTime(LocalDateTime.now().plusSeconds(distance.getTotalDuration()));


        orderMapper.insert(orders);
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();

        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        shoppingCartMapper.clean(userId);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().
                id(orders.getId()).
                orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber()).
                orderAmount(orders.getAmount()).build();

        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        //String numberByUserName = orderMapper.getNumberByUserName(userId);
        paySuccess(ordersPaymentDTO.getOrderNumber());
        OrderPaymentVO vo = new OrderPaymentVO();



        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号: "+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<HistoryOrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<HistoryOrderVO> orders = page.getResult();

        for (HistoryOrderVO order : orders) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            order.setOrderDetailList(orderDetails);
        }

        long total = page.getTotal();

        return new PageResult(total,orders);
    }

    @Override
    public HistoryOrderVO orderDetail(Long id) {

        HistoryOrderVO historyOrderVO = orderMapper.selectById(id);

        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);

        historyOrderVO.setOrderDetailList(orderDetails);

        return historyOrderVO;

    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        HistoryOrderVO historyOrderVO = orderMapper.selectById(id);
        Orders orders = new Orders();
        BeanUtils.copyProperties(historyOrderVO, orders);
        System.out.println("订单状态:"+orders.getStatus());
        if (orders.getStatus() <=3 && orders.getStatus() >= 1){
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            //TODO
            //退款相关修改
            orderMapper.update(orders);
            return;
        }
        if (orders.getStatus()>=4){
            throw new OrderBusinessException("订单状态异常,系统拒绝取消");
        }
    }

    @Override
    public void orderAgain(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);

        for (OrderDetail orderDetail : orderDetails) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(orderDetail, shoppingCart);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = adiminOrderMapper.getById(id);

        if (orders == null) {
            throw new OrderBusinessException("订单为空");
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号: "+orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
